<!--author zyc-->
<template>
  <div>
    <el-card>
      <!-- 筛选区域 -->
      <el-row class="monitor-navbar" type="flex" justify="space-between" align="middle">
        <el-col :span="4">
          <el-menu background-color="#000C34" text-color="#4bc3ec"  :default-active="selectedTab" mode="horizontal">
            <el-menu-item index="detail-info">设备详细信息</el-menu-item>
          </el-menu>
        </el-col>
      </el-row>

      <!-- 列表区 -->
      <div style="height: 60vh">
        <el-skeleton :loading="loading" animated>
          <el-table :data="paginatedData" border height="100%" style="width: 100%; margin-top:20px">
            <el-table-column prop="deviceName" label="设备名称" />
            <el-table-column prop="designPara" label="设计参数" />
            <el-table-column prop="deviceModel" label="设备型号" />
            <el-table-column prop="usageEnviron" label="设备运行环境条件" />

          </el-table>
        </el-skeleton>
      </div>
      <!-- 分页 -->
      <template #footer>
        <div style="margin-top: -30px">
          <Pagination
              :total="total"
              :current-page.sync="searchForm.current"
              :total-pages="totalPages"
              @update:currentPage="handlePageChange"
          />
        </div>
      </template>
    </el-card>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import diApi from "@/api/deviceInformation";
import Pagination from "@/components/Table/Pagination";
import { ElMessage, ElMessageBox } from "element-plus";

const props = defineProps({
  deviceCodes: {
    type: Array,
    default: () => []
  }
});
const router = useRouter();
const route = useRoute(); // 获取当前路由对象
// const deviceCode = route.params.deviceCode;
const deviceCodes = route.params.deviceCodes || [];

// Dom 挂载之后
onMounted(() => {
  getDeviceInformationTableData();
});
// 数据
const inputValue = ref("");
const allTableData = ref([]); // 接收后端全部结果
const tableData = ref([]);
const total = computed(() => tableData.value.length); // 总记录条数
const totalPages = ref(1); // 总页数

const selectedTab = ref('detail-info'); // 默认选中设备信息菜单
// 监听 allTableData 的变化，并同步更新 tableData
watch(allTableData, (newData) => {
  tableData.value = [...newData];
});


watch(total, (newData) => {
  totalPages.value = Math.ceil(newData / searchForm.size);
});

const handlePageChange = (page) => {
  searchForm.current = page;
};

// 搜索条件
const searchForm = reactive({
  current: 1,
  size: 10,
});

const getDeviceInformationTableData = async () => {
  try {
    let res1Data = [];
    let hasError = false;
    let allFailed = true;
    if (Array.isArray(deviceCodes)) {
      for (const code of deviceCodes) {
        try {
          const res = await diApi.getChooseDeviceDetailInfoData({ deviceCodes: code });
          if (res.data && typeof res.data === 'string' && res.data === "暂无设备详细信息") {
            ElMessage.warning(res.data);
            hasError = true;
          } else if (res.data) {
            const res2 = await diApi.getDeviceInfoData();
            if (res2.data.status) {
              const res2Data = res2.data.data;
              res.data.forEach(item1 => {
                const matchingItem2 = res2Data.find(item2 => item2.deivceNo === item1.deivceNo);
                if (matchingItem2) {
                  // 只合并指定的字段
                  item1.deviceModel = matchingItem2.deviceModel || item1.deviceModel;
                  item1.deviceName = matchingItem2.deviceName || item1.deviceName;
                  item1.deviceGrade = matchingItem2.deviceGrade || item1.deviceGrade;
                  item1.counts = matchingItem2.counts || item1.counts;
                  item1.manufacture = matchingItem2.manufacture || item1.manufacture;
                  item1.serviceLife = matchingItem2.serviceLife || item1.serviceLife;
                } else {
                  ElMessage.warning("暂无设备详细信息");
                }
              });
              res1Data = res1Data.concat(res.data);
            } else {
              ElMessage.error("获取第二个 API 数据失败");
              console.log(res2.data.message);
              hasError = true;
            }
            allFailed = false;
          } else {
            ElMessage.error(`获取设备码为${code}的第一个 API 数据失败`);
            console.log(res.data.message);
            hasError = true;
          }
        } catch (innerError) {
          console.error(`Error for device code ${code}:`, innerError);
          hasError = true;
        }
      }
    }

    // 更新 allTableData.value
    allTableData.value = res1Data.map(item => ({...item, selected: false }));

    if (hasError) {
      if (allFailed) {
        ElMessageBox.alert('所有设备信息获取失败', '提示', {
          confirmButtonText: '确定',
        });
        router.push({ name: 'EquipmentInformationDefaultShow' });
      } else {
        ElMessageBox.alert('部分设备信息获取失败', '提示', {
          confirmButtonText: '确定',
        });
      }
    }
  } catch (error) {
    console.error(error);
    if (error.response && error.response.status === 404) {
      ElMessageBox.alert('请求的设备信息未找到', '提示', {
        confirmButtonText: '确定',
      });
      router.push({ name: 'EquipmentInformationDefaultShow' });
    } else {
      ElMessage.error("发生未知错误");
    }
  }
};

// 分页监听
// 计算当前页需要显示的数据
const paginatedData = computed(() => {
  const start = (searchForm.current - 1) * searchForm.size;
  const end = start + searchForm.size;
  return tableData.value.slice(start, end);
});

// 加载 loading 页面
const loading = ref(true);
watch(
    () => paginatedData.value,
    (newValue) => {
      loading.value =!(newValue && newValue.length > 0);
    },
    // 配置项确保在组件挂载时，立即执行一次回调，以根据初始值正确设置 loading 的状态
    { immediate: true } // 立即执行一次，以确保初始值状态正确
);

</script>

<style scoped lang="scss">
#myContainer {
  position: relative;
}
/* 筛选-重置按钮 */
.el-button {
  height: 28px;
  color: #ffffff;
  font-size: 12px;
  border-radius: 3px;
}
#filter-button {
  position: absolute;
  top: 50%;
  left: -150%;
  transform: translate(-50%, -50%);
}
#reset-button {
  background-color: $color-reset-button;
  position: absolute;
  height: 30px;
  color: #ffffff;
  top: 50%;
  left: 200%;
  transform: translate(-50%, -50%);
}
#find-button {
  position: absolute;
  top: 50%;
  left: 3000%;
  width: 100px;
  height: 30px;
  color: #ffffff;
  transform: translate(-50%, -50%);
}
/* card 背景、边框 */
.el-card {
  width: 100%;
  background-color: transparent;
  --el-card-border-color: transparent;
}
/* 数据表背景 */
:deep(.el-table) {
  color: $color-font-table; // 字体颜色
  background-color: transparent;
  --el-table-tr-bg-color: transparent;
  --el-table-header-bg-color: transparent;
  --el-table-row-hover-bg-color: transparent;
  // 鼠标悬停时的行样式
  .el-table__body-wrapper {
    .el-table__row {
      &:hover {
        color: $color-font-table-hover; // 悬停时字体颜色
      }
    }
  }
}

:deep(.el-card__body) {
  padding-top: 0;
}

/* 选中菜单项样式 */
.el-menu-item.is-active {
  color: white!important;
  border: 1px solid #0062ff;
  background-color: #0062ff!important;
  height: 30px;
}
/* 暂时不要分割线 */
.el-menu--horizontal.el-menu {
  border-bottom: 1.5px solid #053789;
  display: block;
  width: 93vw;
}
</style>